<template>
    <div id="ServiceAdd">
        <div id="header">
            <el-button @click="back">返回</el-button>
        </div>
        <!-- 头部 -->
        <div class="title">
            <span>新增项目</span>
        </div>

        <!-- 新增表单 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="demo-ruleForm">
            <el-form-item label="项目名称 :" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>

            <el-form-item label="项目时长 :" prop="time">
                <el-input v-model.number="form.time"></el-input>
            </el-form-item>
            <el-form-item label="项目价格 :" prop="price">
                <el-input v-model="form.price"></el-input>
            </el-form-item>

            <el-form-item label="项目简介 :" prop="introduce">
                <el-input type="textarea" v-model="form.introduce"></el-input>
            </el-form-item>
            <el-form-item label="项目主图 :" prop="mainImg">
                <el-upload
                    class="avatar-uploader"
                    :action="addressHttp"
                    :show-file-list="false"
                    :on-change="handleChange"
                    :auto-upload="false"
                >
                    <img v-if="form.mainImg" :src="addressHttp +'/' +form.mainImg" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>

            <el-form-item label="是否上架 :" prop="shelves">
                <el-radio-group v-model="form.shelves">
                    <el-radio :label="1">上架</el-radio>
                    <el-radio :label="0">不上架</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm('form')">增加</el-button>
                <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import qs from "qs";
import {getTime} from '@/assets/js/public'
export default {
    props: [], // 父辈向子辈传参
    name: "ServiceAdd",
    components: {
        // 组件的引用
    },
    data() {
        let reg = /^[0-9]+.?[0-9]*$/;
        var checkNumber = (rule, value, callback) => {
            if (!reg.test(value)) {
                callback(new Error("该内容必须为数值类型"));
            } else {
                callback();
            }
        };
        return {
            addressHttp: "http://172.16.113.23:8080" /* 图片服务器地址*/,
            form: {
                /* 放增加的数据 */
                name: "",
                time: "",
                price: "",
                introduce: "",
                mainImg: "",
                shelves: "",
                finallyTime: "",
            },
            imgFile: "" /* 装选中的文件 */,

            rules: {
                /* 校验规则 */
                name: [
                    {
                        required: true,
                        message: "请输入项目名称",
                        trigger: "blur",
                    },
                    {
                        min: 3,
                        max: 5,
                        message: "长度在 3 到 5 个字符",
                        trigger: "blur",
                    },
                ],
                time: [
                    {
                        required: true,
                        message: "请输入项目时长",
                        trigger: "blur",
                    },
                    {
                        // type: "number",
                        validator: checkNumber,
                        // message: "时长必须为数字值",
                        trigger: "blur",
                    },
                ],
                price: [
                    {
                        required: true,
                        message: "价格不能为空",
                        trigger: "blur",
                    },
                    {
                        // type: "number",
                        // message: "价格必须为数字值",
                        validator: checkNumber,
                        trigger: "blur",
                    },
                ],
                introduce: [
                    {
                        required: true,
                        message: "请输入项目简介",
                        trigger: "blur",
                    },
                ],
                mainImg: [
                    {
                        required: true,
                        message: "请上传项目主图",
                        trigger: "change",
                    },
                ],
                shelves: [
                    {
                        required: true,
                        message: "请选择是否上架",
                        trigger: "change",
                    },
                ],
            },
        };
    },
    methods: {
        // 点击返回
        back() {
            this.$router.back();
        },

        //当用户选择某个文件的时候
        handleChange(file) {
            console.log(file);
            // 先判断文件的类型和大小
            let fileNameList = file.name.split(".");
            // 文件后缀名
            let res = fileNameList[fileNameList.length - 1];
            console.log(res);
            let typeArr = ["png", "jpg", "jpeg", "webp"];
            if (!typeArr.includes(res)) {
                return this.$message.error(
                    "上传头像图片只能是 jpg,png,jpeg,webp格式!"
                );
            }

            if (file.size / 1024 / 1024 > 2) {
                return this.$message.error("文件大小不能超过2M");
            }

            // this.form.mainImg = URL.createObjectURL(file.raw);
            // console.log(this.form.mainImg);

            this.imgFile = file.raw; /* 将图片装进去 */

            // 文件一定要用formData装起来
            let formData = new FormData();

            formData.append("file", this.imgFile);

            // 发起请求上传图片
            this.$axios({
                url: this.addressHttp + "/ProjectUpload",
                method: "post",
                data: formData,
            })
                .then((res) => {
                    console.log(res);
                    this.form.mainImg = res.data;
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        // 点击增加
        submitForm(formName) {
            console.log("当前时间:" + getTime());
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.form.finallyTime = this.form.time + "分钟";
                    console.log("上架:", this.form.shelves);
                    console.log("时间", this.form);
                    this.$confirm("确定添加该服务吗?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                        .then(() => {
                            // 发起请求
                            this.$axios({
                                url: this.addressHttp + "/project/addProject",
                                method: "post",
                                data: {
                                    name: this.form.name,
                                    price: this.form.price,
                                    time: this.form.finallyTime,
                                    describe: this.form.introduce,
                                    picture: this.form.mainImg,
                                    state: this.form.shelves,
                                    date:getTime()
                                },
                                headers: {
                                    "Content-Type": "application/json",
                                },
                            })
                                .then((res) => {
                                    if (res.code === 200) {
                                        this.$message({
                                            type: "success",
                                            message: "新增成功!",
                                        });
                                        // 跳转至服务管理页面
                                        this.$router.push({ name: "service" });
                                    } else {
                                        this.$message({
                                            type: "error",
                                            message: "新增失败!",
                                        });
                                    }
                                })
                                .catch((err) => {
                                    console.log(err);
                                });
                        })
                        .catch(() => {
                            this.$message({
                                type: "info",
                                message: "已取消新增",
                            });
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {},
};
</script>
    
<style scoped lang='less'>
#ServiceAdd {
    // 头部返回
    #header {
        margin-bottom: 20px;
        .el-button {
            width: 80px;
            height: 30px;
            font-size: 13px;
            text-align: center;
            line-height: 30px;
            line-height: 6px;
            color: #333;
        }
    }

    // 头部样式
    .title {
        width: 70px;
        height: 20px;
        padding-left: 10px;
        border-left: 4px solid #0082cc;
        font-size: 14px !important;
        font-weight: bold;
    }
    // 表单
    .el-form {
        margin-top: 30px;
        .el-form-item {
            margin-bottom: 28px;
            /deep/.el-form-item__label {
                margin-right: 35px;
                width: 100px !important;
            }

            .el-input {
                width: 60%;
            }

            .el-button:nth-of-type(1) {
                margin-left: 50px;
            }
            .el-button:nth-of-type(2) {
                margin-left: 20px;
            }
            /deep/.el-textarea {
                width: 60%;
                .el-textarea__inner {
                    height: 125px;
                }
            }

            /deep/.el-upload {
                border: 3px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                background-color: #f2f2f2;

                &:hover {
                    border-color: #409eff;
                }

                .avatar-uploader-icon {
                    font-size: 28px;
                    color: #8c939d;
                    width: 100px;
                    height: 100px;
                    line-height: 100px;
                    text-align: center;
                }
                .avatar {
                    /* 上传图片后的图片样式 */
                    width: 100px;
                    height: 100px;
                    display: block;
                }
            }

            /deep/.el-form-item__error {
                margin-left: 55px;

                margin-top: 5px;
            }
        }
    }
}
</style>